package server

import (
	"p2p-server/pkg/util"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
)

type P2PServerConfig struct {
	Host          string
	Port          int
	CertFile      string
	KeyFile       string
	HTMLRoot      string
	WebSocketPath string
}

func DefaultConfig() P2PServerConfig {
	return P2PServerConfig{
		Host:          "0.0.0.0",
		Port:          8000,
		HTMLRoot:      "html",
		WebSocketPath: "/ws",
	}
}

type P2PServer struct {
	handleWebSocket func(ws *WebSocketConn, request *ghttp.Request)
	server          *ghttp.Server
	middlewares     []ghttp.HandlerFunc
}

func NewP2PServer(wsHandler func(ws *WebSocketConn, request *ghttp.Request)) *P2PServer {
	server := &P2PServer{
		handleWebSocket: wsHandler,
		server:          g.Server(),
		middlewares:     make([]ghttp.HandlerFunc, 0),
	}
	return server
}

// AddMiddleware 添加中间件
func (server *P2PServer) AddMiddleware(middleware ghttp.HandlerFunc) {
	server.middlewares = append(server.middlewares, middleware)
}

func (server *P2PServer) handleWebSocketRequest(r *ghttp.Request) {
	ws, err := r.WebSocket()
	if err != nil {
		util.Panicf("WebSocket upgrade failed: %v", err)
		return
	}
	wsTransport := NewWebSocketConn(ws)
	server.handleWebSocket(wsTransport, r)
	wsTransport.ReadMessage()
}

func (server *P2PServer) Bind(cfg P2PServerConfig) {
	// 添加中间件
	for _, middleware := range server.middlewares {
		server.server.Use(middleware)
	}
	
	// 设置WebSocket路由
	server.server.BindHandler(cfg.WebSocketPath, server.handleWebSocketRequest)
	
	// 设置静态文件服务
	server.server.SetServerRoot(cfg.HTMLRoot)
	
	// 配置HTTPS
	if cfg.CertFile != "" && cfg.KeyFile != "" {
		server.server.EnableHTTPS(cfg.CertFile, cfg.KeyFile)
	}
	
	// 设置监听地址和端口
	server.server.SetAddr(cfg.Host)
	server.server.SetPort(cfg.Port)
	
	util.Infof("P2P Server listening on:%s:%d", cfg.Host, cfg.Port)
	
	// 启动服务器
	server.server.Run()
}
